package com.lq.nine;

/**
 * @author lq
 * @date 2020-09-28 09:50
 */
public class T5longestPalindrome {

    /**
     * 最长回文字串
     * @param args
     */
    public static void main(String[] args) {
        String r = longestPalindrome("cbbd");
        System.out.println(r);
    }

    public static String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        int len = s.length();
        //二维数组dp[i][j] i <= j, 表示i -> j的字符串是否是回文
        boolean[][] dp = new boolean[len][len];
        char[] chars = s.toCharArray();
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }
        int m = 1;
        int start = 0;
        for (int j = 1; j < len; j++) {
            for (int i = 0; i < j; i++) {
                if(chars[i] != chars[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j] && j - i + 1 > m) {
                    start = i;
                    m = j - i + 1;
                }
            }
        }
        return s.substring(start, start + m);
    }
}
